package com.sinog.front.controller.biz;

import com.sinog.core.util.PhoneUtil;
import com.sinog.core.util.StrUtil;
import com.sinog.core.utilbean.Constants;
import com.sinog.core.utilbean.IdGen;
import com.sinog.front.feign.biz.DadcInfoService;
import com.sinog.front.util.FileUtil;
import com.sinog.front.util.FreemarkerTemplateUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.IOException;
import java.io.PrintWriter;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @desc freemarker引擎模版生成文件导出
 * @author lzq
 * @date 2020-07-24 9:50 上午
 */
@Slf4j
@RestController
public class FileExportController {

    private static final String HC_XXH = "预安置人员核查信息函_";
    private static final String HC_HZD = "预安置人员司法所核查回执单_";
    private static final String XJ_H = "预安置人员衔接函_";
    private static final String XJ_HZD = "预安置人员司法所衔接回执单_";
    private static final String BJ_FANG_AN = "帮教工作方案_";
    @Resource
    private DadcInfoService dadcInfoService;

    /**
     * type=1:核查信息函、type=2:核查信息函回执单、type=3:衔接函、type=4:衔接回执单、type=5:帮教工作方案
     * @param request request
     * @param response response
     */
    @RequestMapping("/azbj/azbjgl/doc/export")
    public void hcHzdExport(HttpServletRequest request,HttpServletResponse response) {
        //1、基本信息准备
        //导出类型
        String type = request.getParameter("type");
        String priNum = request.getParameter("priNum");
        PrintWriter writer = null;
        boolean typeBoolean = StringUtils.isBlank(type) || type.contains("/");
        // if( StrUtil.containsEquals(type,"1","2","3","4","5"){}
        boolean typeValueBoolean = StrUtil.containsEquals(type, Constants.NumberStr.NUM_STR_ONE,
                Constants.NumberStr.NUM_STR_TWO,Constants.NumberStr.NUM_STR_THREE,Constants.NumberStr.NUM_STR_FOUR,Constants.NumberStr.NUM_STR_FIVE);
        boolean priNumBoolean = StringUtils.isBlank(priNum) || priNum.contains("/");
        if(typeBoolean || priNumBoolean || !typeValueBoolean) {
            try {
                response.setContentType("text/html; charset=utf-8");
                writer = response.getWriter();
                writer.println("<script type=\"text/javascript\">alert('请求不合法');window.history.back(-1);</script>");
                writer.flush();
                return;
            } catch(IOException e) {
                log.error("请求不合法:{}",e.getMessage());
                return;
            } finally {
                if(null != writer) {
                    writer.close();
                }
            }
        }
        String realName = "";
        String templateId = "";
        switch(type) {
            case "1":
                realName = HC_XXH;
                templateId = "247399494221777";
                break;
            case "2":
                realName = HC_HZD;
                templateId = "247399494221775";
                break;
            case "3":
                realName = XJ_H;
                templateId = "247399494221888";
                break;
            case "4":
                realName = XJ_HZD;
                templateId = "247399494221885";
                break;
            case "5":
                realName = BJ_FANG_AN;
                templateId = "247399494221999";
                break;
            default:
                break;
        }
        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日");
        String nowDate = sdf.format(date);
        //文档导出父路径
        String pathTemp = FileUtil.getFileTemplatePath();
        String targetPath = pathTemp + realName + nowDate + "_" + IdGen.strid() + File.separator;
        //2、导出所需信息封装（把业务数据查询出来）
        Map<String,Object> dataMap = new HashMap<>(16);
        Map<String,Object> paramMap1 = new HashMap<>(16);
        paramMap1.put("priNum",priNum);
        //1、核查信息函 2、核查信息回执函 3、衔接函 4、衔接回执函 5、安置工作方案
        switch(type) {
            case "1":
                dataMap = dadcInfoService.hcxxh(paramMap1);
                break;
            case "2":
                dataMap = dadcInfoService.hchzd(paramMap1);
                break;
            case "3":
                dataMap = dadcInfoService.xjh(paramMap1);
                break;
            case "4":
                dataMap = dadcInfoService.xjhzd(paramMap1);
                break;
            case "5":
                dataMap = dadcInfoService.bjgzfa(paramMap1);
                break;
            default:
                break;
        }
        if(null == dataMap) {
            try {
                response.setContentType("text/html; charset=utf-8");
                writer = response.getWriter();
                writer.println("<script type=\"text/javascript\">alert('请求不合法');window.history.back(-1);</script>");
                writer.flush();
                return;
            } catch(IOException e) {
                log.error("请求不合法:{}",e.getMessage());
                return;
            } finally {
                if(null != writer) {
                    writer.close();
                }
            }
        }
        //将手机号电话拆分
        Map<String,String> yl = PhoneUtil.splitTelAndPhone((String)dataMap.get("lxdh"));
        dataMap.put("tel",yl.get("tel"));
        dataMap.put("lxdh",yl.get("phone"));
        //年月日拆分
        dataMap.put("yearNow",nowDate.substring(0,4));
        dataMap.put("monthNow",nowDate.substring(5,7));
        dataMap.put("dayNow",nowDate.substring(8,10));
        //3、根据模版ID查询模版名称
        Map<String,Object> tempMap = dadcInfoService.getTemplateName(templateId);
        String tName = (String)tempMap.get("tpath");
        String id = IdGen.strid();
        String sourceFilename = realName + "temp_" + id + ".doc";
        String savePath = FileUtil.getFileTemplatePath();
        String targetFilename = realName + dataMap.get("pname") + "_" + nowDate + ".doc";
        //4、填充模板，生成临时word文件，不带目录
        if(null==dataMap.get(Constants.StrFinalValue.IDNUMOPEN)){
            dataMap.put("idNum",dataMap.get("idNum"));
        }else{
            dataMap.put("idNum",dataMap.get("idnumOpen"));
        }
        FreemarkerTemplateUtil.isSaveWordFileSuccess(dataMap,savePath,targetFilename,tName);
        try {
            FileUtil.downloadFile(request,response,savePath + targetFilename,targetFilename);
        } catch(Exception e) {
            log.error("发生异常:",e);
        }
        //5、下载完成把两个文件都删了
        String delPath = FileUtil.getFileTemplatePath();
        File tempfile = new File(delPath + sourceFilename);
        if(tempfile.exists()) {
            try {
                tempfile.delete();
            } catch(RuntimeException e) {
                log.error(e.getMessage());
            }
        }
        File targetfile = new File(delPath + targetFilename);
        if(targetfile.exists()) {
            try {
                targetfile.delete();
            } catch(RuntimeException e) {
                log.error(e.getMessage());
            }
        }
        File file = new File(targetPath);
        if(file.exists()) {
            FileUtil.deleteDir(file);
        }
    }
}